//
// Created by tcj on 2022/7/17.
//

#ifndef WEB_TEST_WEBSERVER_H
#define WEB_TEST_WEBSERVER_H
#include "iostream"
#include "unordered_map"
#include "unistd.h"
#include "assert.h"
#include "errno.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"

#include "epoll.h"
#include "HTTPconnection.h"
#include "threadpool.h"
#include "timer.h"

namespace tcj{
    class webserver {
    public:
        webserver(int port,int trigMode,int timeoutMs,bool optLinger,int threadNum);
        ~webserver();

        void start();

    private:
        bool initScoet();

        void initEventMode_(int trigMode);

        void addClientCOnnection(int fd,sockaddr_in addr);
        void closeConn(HTTPconnection* client);

        void handleListen();
        void handleWrite_(HTTPconnection* client);
        void handleRead_(HTTPconnection* client);

        void onRead(HTTPconnection* client);
        void onWrite(HTTPconnection* client);
        void onProcess(HTTPconnection* client);

        void sendError(int fd,const char* info);
        void extenTime(HTTPconnection* client);

    private:
        static const int MAX_FD = 65536;
        static int setFdNonbock(int fd);

        int port_;
        int timeoutMs_;
        bool isClose_;
        int listenFd_;
        bool openLinger_;
        char* srcDir_;

        uint32_t listenEvent_;
        uint32_t connectEvent_;

        std::unique_ptr<TimerManager> timer_;
        std::unique_ptr<ThreadPool> threadpool_;
        std::unique_ptr<epoller> epoller_;
        std::unordered_map<int,HTTPconnection> users_;

    };
}



#endif //WEB_TEST_WEBSERVER_H
